package com.strawcom.charmring;

import java.util.Date;
import java.util.List;

import org.litepal.crud.DataSupport;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.strawcom.charmring.bean.Alert;
import com.strawcom.charmring.bean.http.AlarmResponse;
import com.strawcom.charmring.bean.http.BaseResponse;
import com.strawcom.charmring.ui.MainActivity;
import com.strawcom.charmring.util.FormatUtil;
import com.strawcom.charmring.util.LogUtil;
import com.strawcom.charmring.util.PreferenceUtil;

public class PushReceiver extends BroadcastReceiver {

	@Override public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		LogUtil.d("onReceive() action=" + bundle.getInt("action"));
		switch (bundle.getInt(PushConsts.CMD_ACTION)) {

		case PushConsts.GET_MSG_DATA:
			// 获取透传数据
			// String appid = bundle.getString("appid");

			PreferenceUtil.write(context, C.sp.from_push, true);

			byte[] payload = bundle.getByteArray("payload");

			String taskid = bundle.getString("taskid");
			String messageid = bundle.getString("messageid");

			// smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
			boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);

			if (payload != null) {
				String data = new String(payload);
				dealPushMessage(data);
			}
			break;
		case PushConsts.GET_CLIENTID:
			// 获取ClientID(CID)
			// 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
			String cid = bundle.getString("clientid");
			if (!PreferenceUtil.readBoolean(context, C.sp.isBindCidSueecss)) {
				PreferenceUtil.write(context, C.sp.cid, cid);
				App.i().uploadCid(cid);
			}
			LogUtil.d("cid:" + cid);
			break;
		case PushConsts.THIRDPART_FEEDBACK:
			/*
			 * String appid = bundle.getString("appid"); String taskid2 =
			 * bundle.getString("taskid"); String actionid =
			 * bundle.getString("actionid"); String result2 =
			 * bundle.getString("result"); long timestamp =
			 * bundle.getLong("timestamp");
			 * 
			 * LogUtil.d(""appid = " + appid); Log.d("GetuiSdkDemo", "taskid = "
			 * + taskid2); LogUtil.d(""actionid = " + actionid);
			 * LogUtil.d(""result = " + result2); LogUtil.d("timestamp = " +
			 * timestamp);
			 */
			break;
		default:
			break;
		}
	}

	private void dealPushMessage(String data) {
		LogUtil.d("PushReceiver dealPushMessage: " + data);
		Gson gson = new Gson();
		BaseResponse b = gson.fromJson(data, BaseResponse.class);
		if (BaseResponse.PUSH_CODE_ALARM == b.retcode) {
			AlarmResponse alarmResponse = gson.fromJson(data, AlarmResponse.class);
			Alert alert = Alert.convertByAlarmResponse(alarmResponse);

			List<Alert> alist = DataSupport.where("date == ?", alert.getDate()).find(Alert.class);
			if (alist == null || alist.size() < 1) {
				alert.save();
				LogUtil.d("PushReceiver dealPushMessage:broadcast");
				broadcast(ACTION_ALERT, alert.getLat(), alert.getLng(), alert.getName(), alert.getMsg());
			}
			else {
				LogUtil.e("PushReceiver same message . pass");
			}
		}
	}

	public static final String ACTION_ALERT = "com.strawcom.charmring.push.ACTION_ALERT";
	public static final String EXTRA_POINT = "extra_point";
	public static final String EXTRA_LAT = "com.strawcom.charmring.app.EXTRA_LAT";
	public static final String EXTRA_LNG = "com.strawcom.charmring.app.EXTRA_LNG";

	private void broadcast(String action, double lat, double lng, String name, String message) {
		final Intent intent = new Intent(action);
		intent.putExtra(EXTRA_LAT, lat);
		intent.putExtra(EXTRA_LNG, lng);
		App.i().sendBroadcast(intent);

		showAlarmNotifcation(name, message, lat, lng);
	}

	@Deprecated private void showAlarmNotifcation(String  name,String message , double lat, double lng) {
		NotificationManager mNotificationManager = (NotificationManager) App.i().getSystemService(Context.NOTIFICATION_SERVICE);
		// 定义通知栏展现的内容信息
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "告警提示";
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);

		// 定义下拉通知栏时要展现的内容信息
		Context context = App.i().getApplicationContext();
		CharSequence contentTitle = "告警提示";
		CharSequence contentText = "您的好友" + name + "在" + FormatUtil.formatDate(new Date(), FormatUtil.HH_mm) + "发出了告警信息";
		Intent mIntent = new Intent(context, MainActivity.class);
		Alert a = new Alert(name, message , lat , lng);
		String info = new Gson().toJson(a);
		mIntent.putExtra(PushReceiver.EXTRA_POINT,info);
		PendingIntent contentIntent = PendingIntent.getActivity(App.i(), 0, mIntent, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

		// 用mNotificationManager的notify方法通知用户生成标题栏消息通知
		mNotificationManager.notify(1, notification);
	}
}
